package com.demo.javaee.atomic;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @author shenguangyang
 */
public class CasUnsafeExample {
    public static void main(String[] args) throws Exception {
        MyUser myUser = new MyUser();
        // java.lang.SecurityException: Unsafe
        // Unsafe unsafe = Unsafe.getUnsafe();

        Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
        //Field unsafeField = Unsafe.class.getDeclaredFields()[0]; //也可以这样，作用相同
        unsafeField.setAccessible(true);
        Unsafe unsafe =(Unsafe) unsafeField.get(null);

        long offset = unsafe.objectFieldOffset(MyUser.class.getDeclaredField("age"));

        boolean successful;
        unsafe.putInt(myUser, offset,1);
        // 4个参数分别是: 对象实例, 字段的内存偏移量, 字段期望值 , 字段更新值
        successful = unsafe.compareAndSwapInt(myUser, offset, 1, 3);
        System.out.println(successful + "\t" + myUser.age);
        successful = unsafe.compareAndSwapInt(myUser, offset, 3, 5);
        System.out.println(successful + "\t" + myUser.age);
        successful = unsafe.compareAndSwapInt(myUser, offset, 6, 8);
        System.out.println(successful + "\t" + myUser.age);

        offset = unsafe.objectFieldOffset(MyUser.class.getDeclaredField("username"));
        successful = unsafe.compareAndSwapObject(myUser, offset, null, "ha ha ha");
        System.out.println(successful + "\t" + myUser.username);
    }

    public static class MyUser {
        public String username;
        public int age;
    }
}
